package com.example.luke.shengdangxiaoattendance;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.luke.shengdangxiaoattendance.Common.CommonActivity;
import com.example.luke.shengdangxiaoattendance.Database.DingHanDB;
import com.example.luke.shengdangxiaoattendance.Dialog.ClassSelectionDialog;
import com.example.luke.shengdangxiaoattendance.Handler.ClassSetupHandler;
import com.example.luke.shengdangxiaoattendance.Model.ClassBean;
import com.example.luke.shengdangxiaoattendance.Model.Course;
import com.example.luke.shengdangxiaoattendance.Model.PushBean;
import com.example.luke.shengdangxiaoattendance.Model.Setting;
import com.example.luke.shengdangxiaoattendance.Model.StudentAttendance;
import com.example.luke.shengdangxiaoattendance.Util.ExcelUtils;
import com.example.luke.shengdangxiaoattendance.Util.GlobalFunction;
import com.example.luke.shengdangxiaoattendance.http.HttpClient;
import com.example.luke.shengdangxiaoattendance.http.HttpResponseHandler;
import com.example.luke.shengdangxiaoattendance.http.NetWorkConstant;
import com.google.gson.Gson;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.UpgradeInfo;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import okhttp3.Headers;
import okhttp3.Request;

/**
 * Created by luke on 13/06/2017.
 */

public class SettingActivity extends CommonActivity {

    @InjectView(R.id.btn_back)LinearLayout backButton;
    @InjectView(R.id.classTxt)TextView classTxt;
    @InjectView(R.id.ipAd)EditText ipAd;
    @InjectView(R.id.updateNot)TextView updateNot;
    @InjectView(R.id.loopMark)TextView loopMark;
    @InjectView(R.id.pushFrequency)EditText pushFreq;
    ClassSetupHandler classSetupHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting_activity_layout);

        ExcelUtils.verifyStoragePermissions(this);
        initView();



     classSetupHandler   =new ClassSetupHandler(this);

    }

    @Override
    public void initView() {
        super.initView();


        ButterKnife.inject(this);

        pushFreq.setText(Setting.getPushFreq(this)+"");

        if (Setting.defaultClassName.length()!=0)
         classTxt.setText(Setting.defaultClassName);

        ipAd.setText(NetWorkConstant.defaultIp);


        checkUpdateInfo();
        checkLoopMark();

    }

    private void checkUpdateInfo(){//检查版本信息
        String versionName=GlobalFunction.getVersionName(this)+"版本";


        try {

            UpgradeInfo info= Beta.getUpgradeInfo();

            if (info.versionCode>Integer.valueOf(GlobalFunction.getVersionCode(this))){
                GlobalFunction.printTextByTag("asd");
                updateNot.setVisibility(View.VISIBLE);

            }
            else {
                updateNot.setText(""+versionName+"");
            }

        }catch (Exception e){
            updateNot.setText(""+versionName+"");
            e.printStackTrace();
        }

    }

    public void activateLoopMark(View view){//开启app无循环模式
        boolean stat=  Setting.allowLoop(this);


         Setting.saveLoopMode(this,!stat);
        checkLoopMark();
    }


    public void  checkDBPath(View view){


        GlobalFunction.ToastAlert(this, getDatabasePath(DingHanDB.DATABASE_NAME).getPath());
    }
    private void checkLoopMark(){

      boolean stat=  Setting.allowLoop(getApplicationContext());

        if (stat){

            loopMark.setText("已开启");
            GlobalFunction.ToastAlert(this,"已开启循环模式");

        }else {

            loopMark.setText("未开启");
            GlobalFunction.ToastAlert(this,"已关闭循环模式");
        }
    }

    @OnClick(R.id.btn_back)
    public void goBack(){

        showDialog();

    }

//    public void retrieveDataFromHttp(View view){
//
//    }
//
//
//    private void startReqAttendListForClass() {//获取后台考勤数据
//
//        // String temp = classes[currentIndex];
//        GlobalFunction.showProgress(SettingActivity.this, "正在同步考勤数据");
//
//        classSetupHandler.setAttendanceListListener(currentCourse.className, name1.getText().toString(), time.getText().toString(), new ClassSetupHandler.AttendanceListListener() {
//            @Override
//            public void getAttendanceList(ArrayList<StudentAttendance> arrayList) {
//
//                for (StudentAttendance studentAttendance : arrayList) {
//
//                    attendanceList.add(studentAttendance);
//                }
//
//
//
////                            if (arrayList.size() > 0)//如果后台有数据更新
////                            {
////                                attendanceList=arrayList;
////                              //  StudentAttendance.clearAttendanceList(context);
////                                saveAttendanceList();
//
//                //  }
//
//
//                publishProgress();
//
//
//
//            }
//        });
//
//
//    }


    public void popUpClassSelection(View view){
        ArrayList<ClassBean>classBeanArrayList= ExcelUtils.getClassList(this);


        if (classBeanArrayList!=null && classBeanArrayList.size()>0){

            ClassSelectionDialog classSelectionDialog=new ClassSelectionDialog(this);
            classSelectionDialog.setClassBeanArrayList(classBeanArrayList);
            classSelectionDialog.show();
            classSelectionDialog.setClassSelectionListener(new ClassSelectionDialog.ClassSelectionListener() {
                @Override
                public void selectedClass(String className) {

                    classTxt.setText(className);
                    Setting.saveSetting(SettingActivity.this,className);



                }
            });

        }else {
            GlobalFunction.ToastAlert(this,"您没导入好课表");
        }



    }

    public void showDialog(){

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // Set the dialog title
        builder.setTitle("您是否要保存?")
                // Specify the list array, the items to be selected by default (null for none),
                // and the listener through which to receive callbacks when items are selected

                // Set the action buttons
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {



                     if (checkRequirement()){



                            Setting.saveSetting(SettingActivity.this,classTxt.getText().toString().trim());
                            NetWorkConstant.saveNetwork(SettingActivity.this,ipAd.getText().toString());//保存ip地址
                            GlobalFunction.ToastAlert(SettingActivity.this,"保存成功");
                            Setting.savePushFreq(SettingActivity.this,pushFreq.getText().toString());//保存推送频率
                            setResult(RESULT_OK);
                            finish();

                        }
                        // User clicked OK, so save the mSelectedItems results somewhere
                        // or return them to the component that opened the dialog

                    }
                })
                .setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {

                        if (Setting.defaultClassName.length()==0){

                            if (classTxt.getText().length()==0){

                                GlobalFunction.ToastAlert(SettingActivity.this,"课室名称不能为空");


                            }
                        }
                       else {

                            finish();

                        }


                    }
                });

        builder.show();

    }

    private boolean checkRequirement(){



        if (classTxt.getText().toString().equals("-")){

            GlobalFunction.ToastAlert(SettingActivity.this,"请选择课室名称");
            return false;

        }

        if (ipAd.getText().length()==0){
            GlobalFunction.ToastAlert(SettingActivity.this,"IP地址不能为空");
            return false;
        }

        if (pushFreq.getText().toString().equals("0") || pushFreq.getText().length()==0){

            GlobalFunction.ToastAlert(SettingActivity.this,"推送频率不可为空");

            return false;

        }

        if (!NetWorkConstant.isIPAddress(ipAd.getText().toString())){
            GlobalFunction.ToastAlert(SettingActivity.this,"请输入有效ip地址");
            return false;
        }
        return true;

    }

    public void pushAttendance(View view){//推送考勤

       ClassSetupHandler classSetupHandler=new ClassSetupHandler(this);
       classSetupHandler.setPushAttendanceListListener(Setting.defaultClassName, "", GlobalFunction.convertDate(new Date(), "yyyy-MM-dd"), new ClassSetupHandler.PushAttendanceListListener() {
           @Override
           public void donePush(boolean stat) {

           }
       });

        GlobalFunction.printTextByTag(Setting.defaultClassName+"");

    }


    public void checkUpgrade(View view){
        Beta.checkUpgrade();
    }//检查最新版本

    public void chooseClass(View view){

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {

            showDialog();
            return true;
        }


        return super.onKeyDown(keyCode, event);

    }

    public void quitApp(View view){

        this.finishAffinity();

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);


        if (grantResults[0]== PackageManager.PERMISSION_GRANTED)
            ExcelUtils.creatDir(this,"省党校");


    }
}
